package com.ymtc.ibm.code;

import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;

/**
 */
public class MQClientPutGroup {
	private String hostname = "127.0.0.1";
	private int port = 1414; 
	private String channel = "CLIENT.CHL"; 
	private String qManager = "QMA"; 
	private MQQueueManager qMgr; 
	private static String qName = "Q.IN";
	private MQQueue queue;

	public static void main(String[] args) {		
		MQClientPutGroup sp = new MQClientPutGroup();
		sp.runPutMsg();
	}

	public MQClientPutGroup() {

	}
	
	public void MQStart() {
		try {
			MQEnvironment.hostname = hostname; 
			MQEnvironment.channel = channel; 
			MQEnvironment.port = port;
			MQEnvironment.CCSID = 1208;
			
			//Create a connection to the queue manager
			qMgr = new MQQueueManager(qManager);
			int openOptions = MQConstants.MQOO_OUTPUT | MQConstants.MQOO_FAIL_IF_QUIESCING | MQConstants.MQOO_BIND_NOT_FIXED ;
			queue = qMgr.accessQueue(qName, openOptions);
			System.out.println(">>> Open Queue successful!");
		} catch (Throwable ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void MQStop() {
		try {
			queue.close();
			qMgr.disconnect();
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void sendMsgToQueue() {
		try {
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			pmo.options = pmo.options + MQConstants.MQPMO_LOGICAL_ORDER;
			MQMessage msg = new MQMessage();
			int iNo= 1;
			for (int j=0;j<3;j++) {	
				for (int i=0;i<3;i++) {
					msg.writeString("Message" + iNo);
					if (i < 2) {
						msg.messageFlags = MQConstants.MQMF_MSG_IN_GROUP;					
					} else {
						msg.messageFlags = MQConstants.MQMF_LAST_MSG_IN_GROUP;
					}
					queue.put(msg, pmo);
					msg.clearMessage();
					iNo ++ ;
				}
			}
			System.out.println(">>> Put Grouped Message OK!!!");
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void runPutMsg() {
		try {
			MQStart();
			sendMsgToQueue();
			MQStop();
		} catch (Exception e) {
			e.printStackTrace(System.out);
			MQStop();
			System.exit(2);
		}
	}
}